package com.bbs.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bbs.common.entity.SysUser;
import com.bbs.common.entity.User;
import com.bbs.common.exception.CommonException;
import com.bbs.common.mapper.SysUserMapper;
import com.bbs.common.vo.PageVo;
import com.bbs.dto.SysUserListDTO;
import com.bbs.dto.SysUserSaveDTO;
import com.bbs.dto.SysUserUpdateDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * SysUserService
 *
 * @author yangjiajia
 * @since 2024/5/20 11:13
 */
@Service
public class SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    public PageVo<SysUser> list(SysUserListDTO listDTO) {
        Page<SysUser> queryPage = new Page<>(listDTO.getPage(), listDTO.getPageSize());

        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(listDTO.getAccount())) {
            queryWrapper.eq(SysUser::getAccount, listDTO.getAccount());
        }
        if (StringUtils.hasText(listDTO.getName())) {
            queryWrapper.like(SysUser::getName, listDTO.getName());
        }
        IPage<SysUser> page = sysUserMapper.selectPage(queryPage, queryWrapper);
        return new PageVo<>(page);
    }

    /**
     * 添加系统用户
     **/
    public void save(SysUserSaveDTO saveDTO) {

        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getAccount, saveDTO.getAccount());
        if (sysUserMapper.exists(queryWrapper)) {
            throw new CommonException("账号已存在");
        }

        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(saveDTO, sysUser);
        sysUser.setCreateTime(LocalDateTime.now());
        sysUser.setUpdateTime(LocalDateTime.now());
        sysUserMapper.insert(sysUser);
    }

    /**
     * 修改系统用户
     **/
    public void update(SysUserUpdateDTO updateDTO) {
        SysUser sysUser = sysUserMapper.selectById(updateDTO.getId());
        BeanUtils.copyProperties(updateDTO, sysUser);
        sysUserMapper.updateById(sysUser);
    }

    /**
     * 账号锁定
     **/
    public void accountLock(int id) {
        SysUser user = sysUserMapper.selectById(id);
        if (user.getAccount().equals("admin")) {
            throw new CommonException("最高管理员不允许锁定");
        }
        user.setLockFlag(1);
        sysUserMapper.updateById(user);
    }

    /**
     * 账号解锁
     **/
    public void accountUnLock(int id) {
        SysUser user = sysUserMapper.selectById(id);
        user.setLockFlag(0);
        sysUserMapper.updateById(user);
    }
}
